package net.oschina.app;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.content.SharedPreferences;
import android.util.Log;

import net.oschina.app.hjp1.CookieJarImpl;
import net.oschina.app.hjp1.PersistentCookieStore;
import net.oschina.app.hjpbean.UserBean;
import net.oschina.app.ui.ShopService;
import net.oschina.app.util.LogUtils;
import net.oschina.app.util.NetUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * Created by Administrator on 2017/7/13 0013.
 */

public class Myapp extends Application {

    public static Myapp mApp;
    public static OkHttpClient mClient;
    public static ShopService shopService;
    public static  String STATE_LOGIN="state_login";

    public static SharedPreferences sp;
    public static Handler handler;
    public static UserBean userBean;

    /**
     * 连接超时
     */
    public final static int CONNECT_TIMEOUT = 10;
    /**
     * 读取服务器超时
     */
    public final static int READ_TIMEOUT = 10;
    /**
     * 写的超时时间
     */
    public final static int WRITE_TIMEOUT = 10;
    public static boolean isLogIn =false ;


    @Override
    public void onCreate() {
        super.onCreate();
        initOKHttp();
        mApp = this;
        handler = new Handler();
        initOKHttp();
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(Contents.PATH)
                .client(mClient)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
        shopService = mRetrofit.create(ShopService.class);
            sp = getSharedPreferences(STATE_LOGIN,Context.MODE_PRIVATE);
        isLogIn  = sp.getBoolean(STATE_LOGIN,false);
    }

    public static Context getContext() {
        return mApp;
    }


    // 初始化OKHttp实现缓存

    private void initOKHttp() {
        CookieJarImpl cookieJarImpl = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));

        File cacheDir = new File(this.getCacheDir(), "openSourceChina");
        Log.d("bb", this.getCacheDir() + "/openSourceChina");
        mClient = new OkHttpClient
                .Builder()
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                //                 .cookieJar(new CookieJar() {
                //
                //                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
                //
                //                    //保存cookie
                //                    @Override
                //                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                //                        cookieStore.put(url.host(), cookies);
                //
                //                    }
                //                    //读取cookie
                //                    @Override
                //                    public List<Cookie> loadForRequest(HttpUrl url) {
                //                        List<Cookie> cookies = cookieStore.get(url.host());
                //                        return cookies != null ? cookies : new ArrayList<Cookie>();
                //                    }
                //                })
                .cookieJar(cookieJarImpl)

                .cache(new Cache(cacheDir, 10 * 1024 * 1024))
                .addNetworkInterceptor(netInterceptor)
//                .addInterceptor(mInterceptor)


                .build();


    }


    /**
     * 一、无论有无网路都添加缓存。
     * 目前的情况是我们这个要addNetworkInterceptor
     * 这样才有效。经过本人测试（chan）测试有效.
     * 60S后如果没有网络将获取不到数据，显示连接失败
     */
    static Interceptor netInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
          /*String cacheControl = request.header("Cache-Control");
            if (TextUtils.isEmpty(cacheControl)) {
                cacheControl = "public, max-age=60";
            }*/
            int maxAge = 60;
            return response.newBuilder()
                    .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        }
    };


    /**
     * 缓存拦截器  不可用
     */
    Interceptor mInterceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetUtils.hasNetwork(Myapp.getContext())) {
                LogUtils.d("网络不可用 从缓存获取 ");
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            okhttp3.Response response = chain.proceed(request);
            if (NetUtils.hasNetwork(Myapp.getContext())) {
                int maxAge = 60 * 60; // read from cache for 1 minute
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, maxage=" + maxAge)
                        .build();
                LogUtils.d("有网络时 设置缓存" + maxAge + "");
            } else {
                int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
                LogUtils.d("无网络时，设置超时");


            }
            return response;
        }
    };

}
